package cn.itcast.service.cargo.impl;

import cn.itcast.dao.cargo.ExportDao;
import cn.itcast.dao.cargo.PackingDao;
import cn.itcast.dao.cargo.ShippingDao;
import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.Packing;
import cn.itcast.domain.cargo.Shipping;
import cn.itcast.domain.cargo.ShippingExample;
import cn.itcast.service.cargo.ShippingService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class ShippingServiceImpl implements ShippingService {
    @Autowired
    private ShippingDao shippingDao;

    @Autowired
    private PackingDao packingDao;

    @Autowired
    private ExportDao exportDao;

    @Override
    public PageInfo findAll(int page, int size, ShippingExample shippingExample) {
        PageHelper.startPage(page, size);
        List<Shipping> list = shippingDao.selectByExample(shippingExample);
        return new PageInfo(list);
    }

    @Override
    public List<Shipping> findAll(ShippingExample shippingExample) {
        return shippingDao.selectByExample(shippingExample);
    }

    @Override
    public Shipping findById(String id) {
        return shippingDao.selectByPrimaryKey(id);
    }

    @Override
    public void save(Shipping shipping) {
        shipping.setState(0);
        //新增委托单后表明装箱单已经委托，要修改状态
        Packing packing = packingDao.selectByPrimaryKey(shipping.getId());
        packing.setState(1);
        packingDao.updateByPrimaryKeySelective(packing);
        //根据装箱单中的其中一条报运单id查询报运单，将报运单信息赋值给委托单
        String exportIds = packing.getExportIds();
        String[] split = exportIds.split(",");
        String exportId = split[0];
        Export export = exportDao.selectByPrimaryKey(exportId);
        shipping.setPortOfLoading(export.getShipmentPort());
        shipping.setPortOfDischarge(export.getDestinationPort());
        shipping.setLcNo(export.getLcno());
        for (String exportid : split) {
            Export exp = exportDao.selectByPrimaryKey(exportid);
            exp.setState(3);
            exportDao.updateByPrimaryKeySelective(exp);
        }
        //保存委托单
        shippingDao.insertSelective(shipping);
    }

    @Override
    public void update(Shipping shipping) {

    }

    @Override
    public int delete(String id) {
        Shipping shipping = shippingDao.selectByPrimaryKey(id);
        if (shipping.getState() == 0) {
            shippingDao.deleteByPrimaryKey(id);
            return 0;
        }
        return 1;
    }
}
